package ru.dadle8;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import ru.dadle8.model.Customer;

import java.time.Duration;
import java.util.List;
import java.util.Properties;

public class ConsumerWithSerializer extends AbstractConsumer {

    @Override
    public void readMessages(String topicName) {
        Properties properties = getKafkaProperties();
        properties.setProperty("value.deserializer", "ru.dadle8.serializers.CustomerDeserializer");
        KafkaConsumer<String, Customer> consumer = new KafkaConsumer<>(properties);

        //Kafka Consumer subscribes list of topics here.
        consumer.subscribe(List.of(topicName));
        consumer.seekToBeginning(consumer.assignment());
        //print the topic name
        System.out.println("Subscribed to topic " + topicName);

        while (true) {
            ConsumerRecords<String, Customer> records = consumer.poll(Duration.ofMillis(100));

            for (ConsumerRecord<String, Customer> record : records) {
                // print the offset,key and value for the consumer records.
                System.out.println("offset = " + record.offset() + ", key = " + record.key() + ", value = " + record.value());
            }
        }
    }

    public static void main(String[] args) {
        String customersTopicName = "customers";
        ConsumerWithSerializer consumerWithSerializer = new ConsumerWithSerializer();
        consumerWithSerializer.readMessages(customersTopicName);
    }
}
